package com.chaoxi.picturebackend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoxi.picturebackend.model.entity.PictureTag;
import com.chaoxi.picturebackend.service.PictureTagService;
import com.chaoxi.picturebackend.mapper.PictureTagMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import cn.hutool.json.JSONUtil;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 朱杰
 * @description 针对表【picture_tag(图片标签)】的数据库操作Service实现
 * @createDate 2025-09-30 11:57:05
 */
@Service
public class PictureTagServiceImpl extends ServiceImpl<PictureTagMapper, PictureTag>
        implements PictureTagService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String TAG_CACHE_KEY = "picture:tag:list";

    /**
     * 获取所有标签列表，先查询缓存再查询数据库
     *
     * @return 标签列表
     */
    @Override
    public List<PictureTag> list() {
        // 先从Redis缓存中获取
        String cachedTags = stringRedisTemplate.opsForValue().get(TAG_CACHE_KEY);
        if (cachedTags != null) {
            // 如果缓存存在，直接返回缓存数据
            return JSONUtil.toList(cachedTags, PictureTag.class);
//            return Collections.singletonList(JSONUtil.toBean(cachedTags, PictureTag.class));
        }
        // 缓存不存在，查询数据库
        List<PictureTag> tags = super.list();
        // 将查询结果存入Redis缓存，设置较长的过期时间（1小时）
        stringRedisTemplate.opsForValue().set(TAG_CACHE_KEY,
                JSONUtil.toJsonStr(tags),
                6, TimeUnit.HOURS);

        return tags;
    }

    /**
     * 清除标签缓存
     */
    @Override
    public void clearTagCache() {
        stringRedisTemplate.delete(TAG_CACHE_KEY);
    }
}